<?php
class db{

	private $version = '';
	private $stmt = NULL;
	private $link = NULL;
	
	public function __construct()
	{
		$this->connect(config::get("database.dsn"),config::get("database.user"),config::get("database.passwd"));
	}
	
	public function connect($dsn, $user, $password)
	{
		try{
			$this->link = new PDO($dsn, $user, $password);
			@$this->link->exec("alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'");
		}catch (PDOException $e){
			exit(sprintf(lang::get("Can not connect to server:%s!"),$e->getMessage()));
		}
	}

	public function fetch_array($stmt=NULL, $result_type = PDO::FETCH_ASSOC) {
		$stmt = $stmt ? $stmt : $this->stmt;
		return $stmt->fetch($result_type);
	}
	
	public function result_array($stmt=NULL, $result_type = PDO::FETCH_ASSOC) {
		$stmt = $stmt ? $stmt : $this->stmt;
		return $stmt->fetchAll($result_type);
	}

	public function fetch_first($sql) {
		$stmt = $this->query($sql);
		return $this->fetch_array($stmt);
	}

	public function query($sql)
	{
		$this->stmt = $this->link->prepare($sql);
		$this->stmt->execute();
		return $this->stmt;
	}

	public function affected_rows() {
		return $this->stmt->rowCount();
	}
	
	public function exec($sql) {
		return $this->link->exec($sql);
	}

	public function error() {
		return $this->stmt->errorInfo();
	}

	public function errno() {
		return $this->stmt->errorCode();
	}

	public function num_rows($stmt) {
		return $stmt->rowCount();
	}

	public function num_fields($stmt) {
		return $stmt->columnCount();
	}

	public function free_result($stmt) {
		return $stmt = NULL;
	}

	public function insert_id() {
		return $this->link->lastInsertId();
	}

	public function fetch_fields($stmt) {
		return $stmt->fetchColumn();
	}

	public function version() {
		return '5.15';
	}

	public function close() {
		return $this->link = NULL;
	}

	public function halt($message = '', $sql = '') {
		exit($message .":".$sql);
	}
	
	public function createSql($data=array(),$table='',$type="insert",$where='')
	{
		if(!$data) return false;
		$sets = $keys = $vals = array();
		foreach((array)$data as $key => $val) {
			$keys[] = "$key";
			$vals[] = "'$val'";
			$sets[] = "$key = '$val'"; 
		}
		if($type == 'insert'){
			return "INSERT INTO $table (".implode(",",$keys).") VALUES (".implode(",",$vals).")";
		}elseif($type == 'update'){
			return "UPDATE $table SET ".implode(",",$sets)." WHERE $where ";
		}else return false;
	}
	
	public function insert($data,$table)
	{
		if($sql = $this->createSql($data,$table))
		{
			$this->stmt = $this->link->prepare($sql);
			$this->stmt->execute();
			return $this->stmt->execute();
		}
		return false;
	}
	
	public function update($data,$where,$table)
	{
		if($sql = $this->createSql($data,$table,"update",$where))
		{
			$this->stmt = $this->link->prepare($sql);
			return $this->stmt->execute();
		}
		return false;
	}
	
}